// pages/mes/my-orders/my-orders.js
const app = getApp();
import Toast from '../../../component/toast/toast';
import utils from '../../../utils/util.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageSize: 8,
        pageIndex: -1,
        hasMore: true,
        orderList: []
    },
    /**
     * 事件处理
     */
    selectItem(e) {
        let index = e.currentTarget.dataset.index;
        let dataObj = this.data.orderList[index];
        app.globalData.serviceContent = dataObj.ServiceContent;
        let parmas = JSON.stringify(dataObj).replace(/&nbsp;/g, ' ');
        app.globalData.serviceInfo = JSON.parse(parmas);
        wx.navigateTo({
            url: '/pages/service-detail/service-detail?&isShowBuy=false',
        })
    },
    confirmClick(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        console.log(index);
        console.log(this.data.orderList[index])
        let statusCode = this.data.orderList[index].OrderStatus;
        let content = '';
        if (statusCode == 4) {
            wx.showModal({
                title: '提示',
                content: "确认完成，服务费将支付到服务者账户中，不可撤销，请谨慎操作",
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#333',
                confirmText: '确定',
                confirmColor: '#E71015',
                success: function(res) {
                    if (res.confirm) {
                        that.updateOrder(index , 5);
                    }
                }
            });
        } else if (statusCode == 1){
            wx.showModal({
                title: '提示',
                content: "服务者也许正准备接单，你确认要取消订单吗？",
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#333',
                confirmText: '确定',
                confirmColor: '#E71015',
                success: function (res) {
                    if (res.confirm) {

                    }
                }
            });
        } else if (statusCode == 0) {
            wx.showLoading({
                title: '加载中...',
                mask: true
            });
            that.buyService(index);
            return;
        }

    },
    cancelClick(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '提示',
            content: "确认退款，表示你不认可服务者的服务。如退款无正当理由,将损害你的信誉，请谨慎操作",
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#333',
            confirmText: '确定',
            confirmColor: '#E71015',
            success: function (res) {
                if (res.confirm) {
                    that.updateOrder(index, 6);
                }
            }
        });
    },
    /**
     * 网络请求
     */
    updateOrder(index , orderStatus) {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        let that = this;
        let data = {
            OrderId: that.data.orderList[index].Id,
            OrderStatus: orderStatus,
            CurrentUserInfoId: app.userInfo.Id
        };
        console.log("url:" + app.globalData.serverAddress.refundOrderA + "data：" + JSON.stringify(data));
        wx.request({
            url: app.globalData.serverAddress.refundOrderA,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    console.log(res.data);
                    let _statuBo = `orderList[${index}].statuBo`;
                    let _statuBo1 = `orderList[${index}].statuBo1`;
                    let _statuText = `orderList[${index}].statuText`;
                    let _statuTextColor = `orderList[${index}].statuTextColor`;
                    let _statuImg = `orderList[${index}].statuImg`;
                    let statuText = '';
                    let statuTextColor = '#55CAC4';
                    let statuImg = '';
                    if(orderStatus == 5){
                        //确认完成
                        statuText = '已完成';
                        statuImg = '../../../assets/icon/icon_complete.png';
                    }else{
                        //申请退款
                        statuText = '客户申请退款，审核中';
                        statuTextColor = '#FF4F53';
                    }
                    that.setData({
                        [_statuBo]:false,
                        [_statuBo1]:false,
                        [_statuText]:statuText,
                        [_statuImg]: statuImg,
                        [_statuTextColor]: statuTextColor,

                    });
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                Toast("订单提交失败，请检查网络");
                console.log("fail：" + JSON.stringify(res))
            },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    buyService(index) {
        let data = {
            ServiceId: this.data.orderList[index].ServiceId,
            UserInfoId: app.userInfo.Id
        };
        console.log("url:" + app.globalData.serverAddress.payService + "data：" + JSON.stringify(data));
        wx.request({
            url: app.globalData.serverAddress.payService,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function(res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    console.log(res.data)
                    wx.requestPayment({
                        timeStamp: res.data.BodyContent.timeStamp,
                        nonceStr: res.data.BodyContent.nonceStr,
                        package: res.data.BodyContent.package,
                        signType: res.data.BodyContent.signType,
                        paySign: res.data.BodyContent.paySign,
                        success: function(res) {
                            wx.navigateBack({
                                delta: 5,
                            });
                        },
                        fail: function(res) {
                            console.log("fail" + JSON.stringify(res));
                        },
                        complete: function(res) {},
                    })
                }
                Toast(res.data.Message);
            },
            fail: function(res) {
                Toast("订单提交失败，请检查网络");
                console.log("fail：" + JSON.stringify(res))
            },
            complete: function(res) {wx.hideLoading();},
        })
    },
    getMyOrderList() {
        let that = this;
        if (!that.data.hasMore) return;
        let pageI = ++that.data.pageIndex;
        let data = {
            pageSize: that.data.pageSize,
            pageIndex: pageI,
            userInfoId: app.userInfo.Id
        };
        console.log(JSON.stringify(data));
        that.setData({
            pageIndex: pageI
        });
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.getMyOrders,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log(res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let newList = res.data.BodyContent;
                    let flag = true;
                    if (newList != null && newList.length > 0) {
                        newList.forEach(function(item, index) {
                            newList[index]._amount = utils.formatAmount(item.Price);
                            newList[index].statuBo = false;
                            newList[index].statuBo1 = false;
                            newList[index].statuTextColor = '#55CAC4';
                            switch (item.OrderStatus) {
                                case 0:
                                    newList[index].statuBo = true;
                                    newList[index].statuBo1 = false;
                                    newList[index].statuText = '待支付';
                                    newList[index].statu = "去付款";
                                    newList[index].statuImg = '../../../assets/icon/icon_is_confirm.png';
                                    newList[index].isShowWork = false;
                                    break
                                case 1:
                                    newList[index].statuBo = false;
                                    newList[index].statuBo1 = true;
                                    newList[index].statuText = '待服务方确认';
                                    newList[index].statu = "取消订单";
                                    newList[index].statuImg = '../../../assets/icon/icon_is_confirm.png';
                                    newList[index].statuTextColor = '#009014';
                                    newList[index].isShowWork = false;
                                    break;
                                case 2:
                                    newList[index].statuText = '执行中';
                                    newList[index].statuImg = '../../../assets/icon/icon_excuting.png';
                                    newList[index].isShowWork = true;
                                    break;
                                case 4:
                                    newList[index].statuBo = true;
                                    newList[index].statuBo1 = true;
                                    newList[index].statuText = '执行中';
                                    newList[index].statu = "确认完成";
                                    newList[index].statuImg = '../../../assets/icon/icon_excuting.png';
                                    newList[index].isShowWork = true;
                                    break;
                                case 5:
                                    newList[index].statuText = '已完成';
                                    newList[index].statuImg = '../../../assets/icon/icon_complete.png';
                                    newList[index].isShowWork = true;
                                    break;
                                case 6:
                                    newList[index].statuText = '客户申请退款，审核中';
                                    newList[index].statuTextColor = '#FF4F53';
                                    newList[index].isShowWork = true;
                                    break;
                                default:
                                    newList[index].statuText = '待确认';
                                    newList[index].isShowWork = false;
                                    break
                            }
                        });
                        newList = that.data.orderList.concat(newList);
                        // console.log(that.data.pageIndex * that.data.pageSize);
                        if (newList.length < ++that.data.pageIndex * that.data.pageSize) {
                            flag = false;
                        } else {
                            flag = true;
                        }

                    } else {
                        that.setData({
                            hasMore: false
                        });
                        return;
                    }
                    that.setData({
                        orderList: newList,
                        hasMore: flag
                    });
                } else {
                    that.setData({
                        hasMore: false
                    });
                    Toast(res.data.Message);
                }
            },
            fail: function(res) {
                console.log("getCustomerDetail fail:" + JSON.stringify(res))
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.getMyOrderList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        this.getMyOrderList();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})